package org.example.demo.controller;

import java.math.BigInteger;
import org.example.demo.model.CommonResponse;
import org.example.demo.service.backend.CarrierBackendService;
import org.fisco.bcos.sdk.transaction.model.exception.ContractException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/carrier")
public class CarrierController {

    @Autowired
    private CarrierBackendService carrierBackendService;

    // 注册承运商
    @PostMapping("/add")
    public CommonResponse addCarrier(@RequestParam String name, @RequestParam String info, @RequestParam String passwd) {
        // 创建CarrierDTO对象
        org.example.demo.dto.CarrierDTO carrierDTO = new org.example.demo.dto.CarrierDTO();
        carrierDTO.setName(name);
        carrierDTO.setInfo(info);
        carrierDTO.setPasswd(passwd);
        
        boolean ok = carrierBackendService.addCarrier(carrierDTO);
        if (ok) {
            return CommonResponse.ok(ok);
        }
        
        return CommonResponse.fail("4001", new Exception("添加承运商失败"));
    }

    // 验证承运商
    @PostMapping("/check")
    public CommonResponse checkCarrier(@RequestParam int id, @RequestParam String passwd) throws ContractException {
        boolean ok = carrierBackendService.checkCarrier(id, passwd);
        if (ok) {
            return CommonResponse.ok(ok);
        }
        
        return CommonResponse.fail("4001", new Exception("验证承运商失败"));
    }

    // 获取承运商的所有运单
    @PostMapping("/getShipments")
    public CommonResponse getShipmentsByCarrier(@RequestParam int id) throws ContractException {
        BigInteger[] shipments = carrierBackendService.getShipmentsByCarrier(id);
        return CommonResponse.ok(shipments);
    }
}
